package com.study.easyexcel.api.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.study.easyexcel.common.constant.ExcelConstants;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;

/**
 * 生成默认的下拉框
 *
 * @author yuhuan
 * @date 2023/6/27
 */
public class DefaultDropdownBox implements SheetWriteHandler {

    private final int firstRow;
    private final int lastRow;
    private final int firstCol;
    private final int lastCol;

    private String[] explicitList;

    /**
     * 必须指定下拉框在表格中的位置坐标
     */
    public DefaultDropdownBox(int firstRow, int lastRow, int firstCol, int lastCol) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.firstCol = firstCol;
        this.lastCol = lastCol;
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();
        CellRangeAddressList cellRangeList = new CellRangeAddressList(this.firstRow, this.lastRow, this.firstCol, this.lastCol);
        DataValidationConstraint constraint = helper.createExplicitListConstraint(this.explicitList);
        DataValidation dataValidation = helper.createValidation(constraint, cellRangeList);
        boolean showErrorBox = true;
        dataValidation.setShowErrorBox(showErrorBox);
        String title = ExcelConstants.ERR_BOX_TITLE;
        String message = ExcelConstants.ERR_BOX_MESSAGE;
        dataValidation.createErrorBox(title, message);
        sheet.addValidationData(dataValidation);
    }

    /**
     * 设置下拉选项
     */
    public DefaultDropdownBox setExplicitList(List<String> explicitList) {
        this.explicitList = explicitList.toArray(new String[]{});
        return this;
    }
}
